package com.shakespace.artofandroid.chapter04

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.shakespace.artofandroid.R

class CircleView @JvmOverloads constructor(
    context: Context?,
    private val attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    View(context, attrs, defStyleAttr) {

    var color = Color.RED
    val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    init {
        initView()
    }

    private fun initView() {

        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleView)
        color = typedArray.getColor(R.styleable.CircleView_circle_color, Color.RED)
//        val radius = typedArray.getInt(R.styleable.CircleView_radius, 20)

        paint.color = color
        typedArray.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
//        val mode = MeasureSpec.getMode(widthMeasureSpec)
//        if(mode == MeasureSpec.AT_MOST){
//
//        }
        /**
         * resolveSize 的第一个参数， 相当于wrap_content 期望的默认宽/高
         */

        this.setMeasuredDimension(
            Math.max(this.suggestedMinimumWidth, resolveSize(200, widthMeasureSpec)),
            Math.max(this.suggestedMinimumHeight, resolveSize(200, heightMeasureSpec))
        )

    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        /**
         * 方式1 对于直接继承View的控件，如果不对wrap_content做处理，效果和match_parent是一样的对于直接继承View的控件，如果不对wrap_content做处理，效果和match_parent是一样的
         */
//        val width = width
//        val height = height
//        canvas?.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), radius.toFloat(), paint)

        /**
         * 处理padding
         */
        val width = width - paddingLeft - paddingRight
        val height = height - paddingTop - paddingBottom
        val radius = Math.min(width, height) / 2
        canvas?.drawCircle(
            (paddingLeft + width / 2).toFloat(),
            (paddingTop + height / 2).toFloat(),
            radius.toFloat(),
            paint
        )

    }
}